/**
 * This file is part of the CAKIS project.
 * 
 * Copyright (c) 2009-2010 - Florian Arndt, Christian Kerl
 * 
 * @license GNU Lesser General Public License v3 <http://www.opensource.org/licenses/lgpl-3.0.html>
 * @since   15.05.2010
 * @version SVN: $Id: RecipeServiceRemoteImpl.java 143 2010-05-15 12:01:28Z christian-kerl@web.de $
 */
package org.cakis.server.service.impl;

import java.util.UUID;

import org.cakis.server.Names;
import org.cakis.server.model.Recipe;
import org.cakis.server.model.repository.RecipeRepository;
import org.cakis.server.service.RecipeService;
import org.cakis.server.service.session.ClientSession;
import org.cakis.server.service.session.RecipePageRedirectEvent;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.log.Log;

/**
 * RecipeServiceRemoteImpl
 *
 * @author Christian Kerl
 */
@Name(Names.RecipeServiceRemote)
@Scope(ScopeType.APPLICATION)
@Startup
public class RecipeServiceRemoteImpl implements RecipeService.Remote {

    @Logger
    private Log log;
    private RecipeRepository recipeRepository;

    @In(Names.RecipeRepository)
    public void setRecipeRepository(RecipeRepository recipeRepository) {
        this.recipeRepository = recipeRepository;
    }

    @Override
    public void openRecipeInServerSession(String uuid) {
        ClientSession session = (ClientSession)Component.getInstance(ClientSession.class, false);

        if(session != null && session.isInited()) {
            try {
                uuid = stripRecipeUuidPrefix(uuid);
                UUID id = UUID.fromString(uuid);

                Recipe recipe = recipeRepository.findByUuid(id);

                if(recipe == null) {
                    throw new IllegalArgumentException();
                }

                String desc = "Found Recipe '" + recipe.getName() + "'!";

                session.event(
                        new RecipePageRedirectEvent(
                                session.getInfo(),
                                recipe.getId(),
                                desc
                        )
                );
            } catch(IllegalArgumentException e) {
                log.warn("Invalid UUID #0", uuid);
            }
        } else {
            log.error("ClientSession not active or inited!");
        }
    }

    private String stripRecipeUuidPrefix(String uuid) {
        if(uuid != null && uuid.toLowerCase().startsWith(RecipeUuidPrefix.toLowerCase())) {
            uuid = uuid.substring(RecipeUuidPrefix.length());
        }

        return uuid;
    }
}
